﻿using DevComponents.DotNetBar.Controls;
using DevComponents.DotNetBar;
using Public;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Check_Barcode
{
    public partial class Frm_Model : Form
    {
        string[] cols1 = { "ID", "机型", "类别", "条码规则", "创建时间", };
        string[] names1 = { "ID", "model", "category", "barcode_rule", "create_time" };
        string dbstr = "";
        DBAccessOperater db1;
        public Frm_Model()
        {
            InitializeComponent();
        }
        private void Frm_Model_Load(object sender, EventArgs e)
        {
            dbstr = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Application.StartupPath + @"\\DB\Location.mdb";//Access数据库相对路径;);
            db1 = new DBAccessOperater(dbstr);
            Tools.initDataView(dataGridViewX1, cols1, names1);
            保存ToolStripMenuItem.Enabled = false;
            RefreshData();
        }
        private void RefreshData()
        {
            string sql2 = $@"select * from tbl_model_rule   ";
            DataTable dt2 = db1.SelectDataBase(sql2);
            dataGridViewX1.DataSource = dt2;
        }
        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void 增加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel1.Enabled = true;
            label_status.Text = "新增";

            修改ToolStripMenuItem.Enabled = true;
            保存ToolStripMenuItem.Enabled = true;
        }

        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel1.Enabled = true;
            label_status.Text = "编辑";
            修改ToolStripMenuItem.Enabled = true;
            保存ToolStripMenuItem.Enabled = true;
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int selectedRowIndex = dataGridViewX1.SelectedCells[0].RowIndex;
            DataGridViewRow selectedRow = dataGridViewX1.Rows[selectedRowIndex];
            int id = Convert.ToInt32(selectedRow.Cells["ID"].Value);
            DialogResult dr = MessageBoxEx.Show("确认要删除这条记录吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                string SQL = $@"DELETE FROM [tbl_model_rule] WHERE ID={id} ";
                int res = db1.ExcuteSQL(SQL);
                if (res > 0)
                {
                    MessageBoxEx.Show("删除成功");
                }
                else
                {
                    MessageBoxEx.Show("删除失败");
                }
                RefreshData();
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (label_status.Text == "详览")
            {
                MessageBoxEx.Show("请新增/编辑");
                return;
            }
            if (string.IsNullOrEmpty(model.Text))
            {
                Tools.ShowError("请填写机型");
                return;
            }
            if (string.IsNullOrEmpty(category.Text))
            {
                Tools.ShowError("请填写类别");
                return;
            }
            if (label_status.Text == "新增")
            {
                string chk = $@"select * from [tbl_model_rule] where model='{model.Text}' and category ='{category.Text}' ";
                bool ex = db1.CheckSQL(chk);
                if (ex)
                {
                    Tools.ShowError("该机型分类已经存在了");
                    return;
                }
                string SQL = $@"INSERT INTO [tbl_model_rule] ([model], [category],[barcode_rule], [create_time]) VALUES ('{model.Text}','{category.Text}','{barcode_rule.Text}', '{DateTime.Now}') ";
                int res = db1.ExcuteSQL(SQL);
                if (res > 0)
                {
                    Tools.ShowInformation("保存成功");
                }
                else
                {
                    Tools.ShowError("保存失败");
                }
            }
            if (label_status.Text == "编辑")
            {
                int selectedRowIndex = dataGridViewX1.SelectedCells[0].RowIndex;
                DataGridViewRow selectedRow = dataGridViewX1.Rows[selectedRowIndex];
                int id = Convert.ToInt32(selectedRow.Cells["ID"].Value);
                string SQL = $@"update [tbl_model_rule] set model='{model.Text}',category ='{category.Text}' ,barcode_rule ='{barcode_rule.Text}' where id={id}  ";
                int res = db1.ExcuteSQL(SQL);
                if (res > 0)
                {
                    Tools.ShowInformation("保存成功");
                }
                else
                {
                    Tools.ShowError("保存失败");
                }
            }
            RefreshData();
            //string sql2 = $@"select * from tbl_prod_sn_rule where itm_cd='{ITEM_NO.Text}'  ";
            //DataTable dt2 = db.SelectDataBase(sql2);
            //if (dt2.Rows.Count <= 0)
            //{
            //    tool.ShowInformation($"{ITEM_NO.Text}没有定义条码规则");
            //    return;
            //}
            panel1.Enabled = true;
            label_status.Text = "详览";

        }

        private void dataGridViewX1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //dataGridView添加行号
            try
            {
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                    Convert.ToInt32(e.RowBounds.Location.Y + (e.RowBounds.Height - dataGridViewX1.RowHeadersDefaultCellStyle.Font.Size) / 2),
                    dataGridViewX1.RowHeadersWidth - 4, e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                    dataGridViewX1.RowHeadersDefaultCellStyle.Font, rectangle, dataGridViewX1.RowHeadersDefaultCellStyle.ForeColor,
                    TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                Console.Write("dgv1_RowPostPaint：" + ex.Message);
            }
        }
        string _ID;
        private void dataGridViewX1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewX1.CurrentRow != null)
            {
                _ID = dataGridViewX1.CurrentRow.Cells["ID"].Value != null ? dataGridViewX1.CurrentRow.Cells["ID"].Value.ToString() : "";
                model.Text = dataGridViewX1.CurrentRow.Cells["机型"].Value != null ? dataGridViewX1.CurrentRow.Cells["机型"].Value.ToString() : "";
                category.Text = dataGridViewX1.CurrentRow.Cells["类别"].Value != null ? dataGridViewX1.CurrentRow.Cells["类别"].Value.ToString() : "";
                barcode_rule.Text = dataGridViewX1.CurrentRow.Cells["条码规则"].Value != null ? dataGridViewX1.CurrentRow.Cells["条码规则"].Value.ToString() : "";
            }
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewX1.RowCount <= 0)
            {
                MessageBox.Show("无数据，不能导出");
                return;
            }

            string saveFile, title;
            saveFileDialog1.FileName = this.Text + "" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                saveFile = saveFileDialog1.FileName;
                title = saveFileDialog1.Title;

                saveFileDialog1.Filter = "Excel文件（*.xls）|*.xls";//设置文件类型 
                saveFileDialog1.FilterIndex = 1;//设置默认文件类型显示顺序
                //ExportReport Excel_daochu = ExportReport.INSTANCE();
                //Excel_daochu.ExportExcel(DGV_明细, saveFile.ToString(), "条码数据明细");
                ExcelHelperForNPOI.TableToExcel(Tools.GetDgvToTable(dataGridViewX1), saveFile.ToString());
            }
            else { return; }
        }
        bool flag = true;
        protected DataTable dt = new DataTable();
        private void 导入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flag = true;
            DialogResult dr = openFileDialog1.ShowDialog();
            if (DialogResult.OK != dr)
            {
                return;
            }

            string _FilePath = openFileDialog1.FileName;
            if (_FilePath == "")
            {
                return;
            }

            if (!File.Exists(_FilePath))
            {
                return;
            }
            //FilePath.Text = _FilePath;
            dt.Clear();
            DataTable errorTable = new DataTable();
            dt = ExcelHelperForNPOI.ExcelToTable(_FilePath);
            this.dataGridViewX1.DataSource = dt;
            FrmProgressBar panelProgress = new FrmProgressBar();
            panelProgress.Show();
            float percent;
            int rowCount = dataGridViewX1.Rows.Count;
            int i = 0;
            try
            {
                int res = 0;
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    string _model = dt.Rows[k]["机型"] + "";
                    string _category = dt.Rows[k]["类别"] + "";
                    string _barcode_rule = dt.Rows[k]["条码规则"] + "";

                    string chk = $@"select * from [tbl_model_rule] where model='{_model}' and category ='{_category}' ";
                    bool ex = db1.CheckSQL(chk);
                    if (ex)
                    {
                        Tools.ShowError($@"该机型分类 {_model},{_category}. 已经存在了");
                        return;
                    }
                    else 
                    {
                        string SQL = $@"INSERT INTO [tbl_model_rule] ([model], [category],[barcode_rule], [create_time]) VALUES ('{_model}','{_category}','{_barcode_rule}', '{DateTime.Now}') ";
                        res += db1.ExcuteSQL(SQL);
                    }

                    
                    percent = ((float)(i++) * 100) / rowCount;
                    panelProgress._进度条.Text = percent.ToString("n") + "%";
                    panelProgress.progressBar1.Value = Convert.ToInt32(percent);
                    System.Windows.Forms.Application.DoEvents();
                }
                if (res > 0)
                {
                    Tools.ShowInformation($@"成功导入{res}条记录");
                }
                else
                {
                    Tools.ShowError("保存失败");
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                panelProgress.Close();
                RefreshData();
            }
            
        }
    }
}
